package json;

import cn.hutool.json.JSONUtil;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class JSONTest01 {


    //JSONUtil.toJsonStr,对象转json
    @Test
    public void testObjectToJson() {
        Student student = new Student(1, "zhangsan", "nan", 18);
        String jsonStr = JSONUtil.toJsonStr(student);
        System.out.println(jsonStr);
    }
   //JSONUtil.toBean(jsonStr, Student.class);，json转对象
    @Test
    public void testJsonToObject() {
        String jsonStr="{\"sno\":1,\"sname\":\"zhangsan\",\"gender\":\"nan\",\"age\":18}";
        Student student = JSONUtil.toBean(jsonStr, Student.class);
        System.out.println(student.getSno());
    }
//JSONUtil.toJsonStr(students);集合转json
    @Test
    public void testArrayToJson() {
        List<Student> students = Arrays.asList(
                new Student(20131210, "无忌", "男", 25),
                new Student(20131223, "敏敏", "女", 20)
        );
        String jsonStr = JSONUtil.toJsonStr(students);
        System.out.println(jsonStr);
        System.out.println(JSONUtil.formatJsonStr(jsonStr));//打印格式化好的
    }
// JSONUtil.parseArray(jsonStr).toList(Student.class);json转集合
    @Test
    public void testJsonToArray() {
        String jsonStr = "[{\"sno\":20131150,\"sname\":\"老王\",\"gender\":\"男\",\"age\":30},{\"sno\":20131370,\"sname\":\"老李\",\"gender\":\"女\",\"age\":27}]";
        List<Student> students = JSONUtil.parseArray(jsonStr).toList(Student.class);

        for (Student student : students) {
            System.out.println(student);
        }
    }
//map集合转json
    //1.
    @Test
    public void testMapToJson() {
        //1.创建一个集合,里面存放两个学生对象
        List<Student> students = Arrays.asList(
                new Student(20131210, "无忌", "男", 25),
                new Student(20131223, "敏敏", "女", 20)
        );

        //2.将students集合转换成Map集合
        Map<String, Student> map = students.stream().collect(Collectors.toMap(student -> student.getSno() + "", student -> student));
        //3.将map转换成json串
        System.out.println(JSONUtil.toJsonPrettyStr(map));

    }

}
